var redis=require("redis");
var log=require("../utils/log");

var game_redis=null;
function connect_to_redis(host,port,db_index){
		game_redis=redis.createClient({
		host:host,
		port:port,
		db:db_index
	});

	game_redis.on("error",function(err){
		log.error(err);
	});
}

function set_game_info_inredis(id,info){
	if (game_redis==null)
		return;

	var key="game_user_id_"+id;
	game_redis.hmset(key,info,function(err){
		if(err){
			log.error(err);
			return {err:1};
		}
	});
}

function update_game_info_inredis(id,field,increment){
	if (game_redis==null)
		return;

	var key="game_user_id_"+id;
	//增量值
	game_redis.hincrby(key,field,increment);

	//不好的方法
	/*game_redis.hgetall(key,function(err,data){
		if (err){
			log.error(err);
			return {err:1};
		}
		var result={
			exp:data.exp,
			chip:data.chip,
			game_vip:data.game_vip,
		};
		result[param_str]=parseInt(result[param_str])+plus_value;
		
		game_redis.hmset(key,result,function(err){
			if(err){
				log.error(err);
				return {err:1};
			}
		});

		return {err:0,result};
	});*/
}

function get_game_info_inredis(id,call_back){
	if (game_redis==null)
		return;

	var key="game_user_id_"+id;
	game_redis.hgetall(key,function(err,data){
		if (err){
			call_back({err:1});
			return;
		}
		var result={
			exp:data.exp,
			chip:data.chip,
			game_vip:data.game_vip,
		};
		call_back({err:0,result});
		return;
	});
}

function set_game_world_rank(id,chip){
	if (game_redis==null)
		return;

	var key="game_world_rank";
	//chip作为排行的权重
	game_redis.zadd(key,chip,id);

}

function get_game_world_rank(call_back){
	if (game_redis==null)
		return;

	var key="game_world_rank";
	game_redis.zrevrange(key,0,10,"withscores",function(err,data){
		if (err){
			call_back({err:1});
			return;
		}

		var result=[];

		for (var i=0;i<data.length;i++){
			//转成数字
			result[i]=parseInt(data[i]);
		}
		call_back({err:0,result});
		return;
	});

}

function update_game_world_rand(id,increment){
	if (game_redis==null)
		return;

	var key="game_world_rank";
	//增量值
	game_redis.zincrby(key,increment,id);
}

module.exports={
	connect:connect_to_redis,
	set_game_info_inredis:set_game_info_inredis,
	get_game_info_inredis:get_game_info_inredis,
	update_game_info_inredis:update_game_info_inredis,
	set_game_world_rank:set_game_world_rank,
	get_game_world_rank:get_game_world_rank,
	update_game_world_rand:update_game_world_rand,
};